package net.j4love.netty.inaction.c2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author he peng
 * @create 2018/6/12 12:50
 * @see
 */
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    // 在连接被建立时调用
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String msg = "hello Netty! I started to learn netty.";
        ctx.writeAndFlush(Unpooled.copiedBuffer(msg , CharsetUtil.UTF_8));
        System.out.println("[" + Thread.currentThread().getName() + "] Thread , Channel Active , Send Msg -> " + msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("[" + Thread.currentThread().getName() + "] Thread ," +
                " Client Received : " + msg.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("[" + Thread.currentThread().getName() + "] Thread , " +
                "Exception Caught , Remote Address [" + ctx.channel().remoteAddress() + "]");
        try {
            cause.printStackTrace();
        } finally {
            ctx.close();
        }
    }
}
